package com.ytjj.qmyx.mall.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.ytjj.common.constants.CopyWriterConstant;
import com.ytjj.common.constants.QueueConstants;
import com.ytjj.common.constants.SysConfigConstants;
import com.ytjj.common.dto.mqdto.OrderRecordDto;
import com.ytjj.common.exception.ApiException;
import com.ytjj.common.service.RedisService;
import com.ytjj.common.utils.CopyWriterConfigUtil;
import com.ytjj.common.utils.OrderUtils;
import com.ytjj.common.utils.SysConfigUtil;
import com.ytjj.qmyx.mall.constants.RedisConstants;
import com.ytjj.qmyx.mall.mapper.OrdersSpecMapper;
import com.ytjj.qmyx.mall.mapper.ProductMapper;
import com.ytjj.qmyx.mall.mapper.ProductSpecMapper;
import com.ytjj.qmyx.mall.model.Orders;
import com.ytjj.qmyx.mall.model.OrdersInfo;
import com.ytjj.qmyx.mall.model.Product;
import com.ytjj.qmyx.mall.model.ProductSpec;
import com.ytjj.qmyx.mall.model.request.CreateOrderRequest;
import com.ytjj.qmyx.mall.model.response.CartProductResponse;
import com.ytjj.qmyx.mall.model.response.ProductResponse;
import com.ytjj.qmyx.mall.model.response.ProductSpecResponse;
import com.ytjj.qmyx.mall.service.CreateOrderService;
import com.ytjj.qmyx.mall.service.OrdersService;
import com.ytjj.qmyx.mall.service.ProductService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 购物车创建订单的方式
 *
 *
 * @version 1.0
 *
 */
@Slf4j
@Service("CARTV2")
public class OrdersCartV2ServiceImpl implements CreateOrderService<CreateOrderRequest>  {

    @Autowired
    private RedisService redisService;

    @Autowired
    private ProductService productService;

    @Autowired
    private OrdersService ordersService;

    @Resource
    private SysConfigUtil sysConfigUtil;

    @Resource
    private CopyWriterConfigUtil copyWriterConfigUtil;

    @Resource
    private RabbitTemplate rabbitTemplate;

    @Resource
    private OrdersSpecMapper ordersSpecMapper;

    @Resource
    private ProductMapper productMapper;
    @Resource
    private ProductSpecMapper productSpecMapper;

    @Override
    @Transactional
    public Integer createOrder(CreateOrderRequest request) {
        String orderParentNo = OrderUtils.getOrderCode(request.getUserId());//组合订单号
        // 购物车创建订单
        String[] carts = request.getCartNo();
        // 从缓存中取出购物车信息，并且删除
        List<CartProductResponse> responses = Arrays.asList(carts).stream()
                .map(item -> {
                    log.info("-----根据购物车编号获取商品-----编号【{}】",RedisConstants.CART_KEY_V2 + request.getUserId());
                    String json = redisService.getMapString(RedisConstants.CART_KEY_V2 + request.getUserId(), item);
                    log.info("-----根据购物车编号获取商品-----结果【{}】",json);
                    CartProductResponse cartResponse = JSONObject.parseObject(json, CartProductResponse.class);
                    log.info("-----根据购物车编号获取商品-----准备删除");
                    redisService.delete(RedisConstants.CART_KEY_V2 + request.getUserId(), item);
                    log.info("-----根据购物车编号获取商品-----删除");
                    return cartResponse;
                }).collect(Collectors.toList());
        log.info("-----购物车===");
        BigDecimal realTotalMoney = new BigDecimal(0);
        BigDecimal goodsMoney = new BigDecimal(0);
        // 计算商品总价格
        for(CartProductResponse item : responses){
            log.info("===item==={}", item);
            // 普通商品
            ProductSpec productSpec = productService.getProductSpecById(request.getProductSpecId());
//            ProductResponse product = productService.getProductById(productSpec.getProductId(),request.getPageSourceV2());

            // 判断库存是否存在----------冻结库存前查一下库存是否足够用
            log.info("=============冻结库存前查一下库存是否足够用4=====================参数{},{}",productSpec.getProductId(), item.getSpecId());

            if (Integer.valueOf(sysConfigUtil.getSysConfig(SysConfigConstants.IS_STOCE_VERIFY)) > 0) {
                boolean b = ordersService.checkProductStock(productSpec.getProductId(), item.getSpecId(),item.getProductSum());
                if (!b) {
                    throw new ApiException(copyWriterConfigUtil.getCopyWriterValue(CopyWriterConstant.INSUFFICIENT_STOCK));
                }
            }
            if (null == item.getProductSum()){
                item.setProductSum(1);
            }
            if(item.getIsDirectBuy()!= null && item.getIsDirectBuy() == 1){
                realTotalMoney = realTotalMoney.add(productSpec.getCurPrice().multiply(BigDecimal.valueOf(item.getProductSum())));
            }else{
                realTotalMoney = realTotalMoney.add(productSpec.getPrice().multiply(BigDecimal.valueOf(item.getProductSum())));
            }
            goodsMoney = goodsMoney.add(productSpec.getOriginalPrice().multiply(BigDecimal.valueOf(item.getProductSum())));

        }

        // 主订单
        Orders orders = ordersService.saveOrders(request.getUserId(), request.getTel(),
                goodsMoney.setScale(2, BigDecimal.ROUND_UP),
                realTotalMoney.setScale(2, BigDecimal.ROUND_UP),
                request.getOrderSource(),request.getChannel(),0,orderParentNo);
        // 订单明细
        responses.stream().map(item -> {
            // 普通商品
            ProductSpec productSpec = productService.getProductSpecById(request.getProductSpecId());
            ProductResponse product = productService.getProductById(productSpec.getProductId(),request.getPageSourceV2());
//            if (Integer.valueOf(sysConfigUtil.getSysConfig(SysConfigConstants.IS_STOCE_VERIFY)) > 0 && productSpec.getStock() <= 0) {
//                throw new ApiException(copyWriterConfigUtil.getCopyWriterValue(CopyWriterConstant.INSUFFICIENT_STOCK));
//            }
            BigDecimal price = productSpec.getPrice();
            if(item.getIsDirectBuy() == 1){
                price = productSpec.getCurPrice();
            }
            OrdersInfo ordersInfo = ordersService.saveOrdersInfo(orders.getId(), product.getId(), product.getProductName(), product.getProductImg(),
                    price, productSpec.getOriginalPrice(), product.getWarehouse(), product.getWarehouseName(),
                    product.getWarehouseRule(), request.getSpecialId(), productSpec.getSkuSpec(), product.getBankerId(),
                    productSpec.getId(), product.getActivityType(), null, product.getActivityMax(), product.getActivityMin(),product.getDescr(),
                    item.getIsDirectBuy(),request.getPageSourceV2(),null,product.getProductType(),0, productSpec.getCostPrice(), productSpec.getThreeSkuId(),item.getProductSum(),"",null);

            try {
                //记录订单规格信息
                ProductSpec productSpecs = ordersSpecMapper.selectOrderSpec(item.getSpecId());
                log.info("========productSpecs========{}",productSpecs);
                log.info("========productSpecs.getSkuSpec()========{}",productSpecs.getSkuSpec());
                log.info("========orders.getId()========{}",orders.getId());
                log.info("========orders.getId()========{}",orders.getId());
                log.info("========productSpecs.getPrice()========{}",productSpecs.getPrice());
                log.info("========productSpecs.getCostPrice()========{}",productSpecs.getCostPrice());
                ordersSpecMapper.insertOrderSpec(productSpecs.getSkuSpec(),orders.getId(),productSpecs.getPrice(),productSpecs.getOriginalPrice(),productSpecs.getCostPrice());

            }catch (Exception e){
                log.error("记录订单规格表异常",e);
            }
            return ordersInfo;
        }).collect(Collectors.toList());
        return orders.getId();
    }

    @Override
    @Transactional
    public Integer cartCreateOrder(CreateOrderRequest request) {

        // 购物车创建订单
        String[] carts = request.getCartNo();
        // 从缓存中取出购物车信息，并且删除
        List<CartProductResponse> responses = Arrays.asList(carts).stream()
                .map(item -> {
                    log.info("-----根据购物车编号获取商品-----编号【{}】",RedisConstants.CART_KEY_V2 + request.getUserId());
                    String json = redisService.getMapString(RedisConstants.CART_KEY_V2 + request.getUserId(), item);
                    log.info("-----根据购物车编号获取商品-----结果【{}】",json);
                    CartProductResponse cartResponse = JSONObject.parseObject(json, CartProductResponse.class);
                    log.info("-----根据购物车编号获取商品-----准备删除");
                    redisService.delete(RedisConstants.CART_KEY_V2 + request.getUserId(), item);
                    log.info("-----根据购物车编号获取商品-----删除");
                    return cartResponse;
                }).collect(Collectors.toList());
        log.info("-----购物车");
//        BigDecimal realTotalMoney = new BigDecimal(0);
//        BigDecimal goodsMoney = new BigDecimal(0);
//        // 计算商品总价格
//        for(CartProductResponse item : responses){
//            // 普通商品
//            ProductResponse product = productService.getProductById(item.getId(),request.getPageSourceV2());
//            // 判断库存是否存在
//            if (Integer.valueOf(sysConfigUtil.getSysConfig(SysConfigConstants.IS_STOCE_VERIFY)) > 0 && product.getStock() <= 0) {
//                throw new ApiException(copyWriterConfigUtil.getCopyWriterValue(CopyWriterConstant.INSUFFICIENT_STOCK));
//            }
//            ProductSpecResponse productSpec = productService.getProductSpecInfoById(item.getSpecId());
//            if(item.getIsDirectBuy()!= null && item.getIsDirectBuy() == 1){
//                realTotalMoney = realTotalMoney.add(product.getCurPrice());
//            }else{
//                realTotalMoney = realTotalMoney.add(productSpec.getPrice());
//            }
//            goodsMoney = goodsMoney.add(product.getOriginalPrice());
//        }
        //拆单
        Integer orderParentNo = createOrderByCartNo(responses, request);
        return orderParentNo;
    }

    /**
     * 拆单
     * @param responses
     * @return
     */
    private Integer createOrderByCartNo(List<CartProductResponse> responses, CreateOrderRequest request) {
        //根据bankerId分组
//        Map<Integer, List<CartProductResponse>> groupMap =
//                responses.stream().collect(Collectors.groupingBy(CartProductResponse::getBankerId,Collectors.toList()));
//        Set<Integer> integers = groupMap.keySet();
        String orderParentNo = OrderUtils.getOrderCode(request.getUserId());//组合订单号
        Integer result = null;
        Integer productSum = 1;
        for (CartProductResponse response : responses) {
            Map<String, BigDecimal> moneyMap = calculationMoneyByProduct(response);
            BigDecimal realTotalMoney = moneyMap.get("realTotalMoney");
            BigDecimal goodsMoney = moneyMap.get("money");
            productSum = response.getProductSum();
            Orders orders = ordersService.saveOrders(request.getUserId(),
                    request.getTel(),
                    goodsMoney.setScale(2, BigDecimal.ROUND_UP),
                    realTotalMoney.setScale(2, BigDecimal.ROUND_UP),
                    request.getOrderSource(),
                    request.getChannel(),
                    0,
                    orderParentNo);

            // 订单明细
            ProductResponse product = productService.getProductById(response.getId(),request.getPageSourceV2());
            ProductSpec productSpec = productService.getProductSpecById(request.getProductSpecId());

            // 判断库存是否存在----------冻结库存前查一下库存是否足够用
            log.info("=============冻结库存前查一下库存是否足够用3=====================参数{},{}",productSpec.getProductId(), response.getSpecId());
            boolean b = ordersService.checkProductStock(product.getId(), response.getSpecId(),request.getProductSum());

            if (!b) {
                throw new ApiException(copyWriterConfigUtil.getCopyWriterValue(CopyWriterConstant.INSUFFICIENT_STOCK));
            }

//            if (Integer.valueOf(sysConfigUtil.getSysConfig(SysConfigConstants.IS_STOCE_VERIFY)) > 0 && productSpec.getStock() <= 0) {
//                throw new ApiException(copyWriterConfigUtil.getCopyWriterValue(CopyWriterConstant.INSUFFICIENT_STOCK));
//            }
            OrdersInfo ordersInfo = ordersService.saveOrdersInfo(orders.getId(), product.getId(), product.getProductName(), product.getProductImg(),
                    productSpec.getPrice(), product.getOriginalPrice(), product.getWarehouse(), product.getWarehouseName(),
                    product.getWarehouseRule(), request.getSpecialId(), productSpec.getSkuSpec(), product.getBankerId(),
                    productSpec.getId(), null, null, null, null,product.getDescr(),
                    0,request.getPageSourceV2(),null,1,0, productSpec.getCostPrice(),productSum);
            try {
                // 记录订单规格信息
                ProductSpec productSpecs = ordersSpecMapper.selectOrderSpec(request.getProductSpecId());
                ordersSpecMapper.insertOrderSpec(productSpecs.getSkuSpec(),orders.getId(),productSpecs.getPrice(),productSpecs.getOriginalPrice(),productSpecs.getCostPrice());
            }catch (Exception e){
                log.error("发送到rabbitmq错误",e);
            }
            result = orders.getId();
        }

//        for (Integer bankerId : integers) {
//            Map<String, BigDecimal> moneyMap = calculationMoney(bankerId, responses);
//            BigDecimal realTotalMoney = moneyMap.get("realTotalMoney");
//            BigDecimal goodsMoney = moneyMap.get("money");
//
//            Orders orders = ordersService.saveOrders(request.getUserId(),
//                    request.getTel(),
//                    goodsMoney.setScale(2, BigDecimal.ROUND_UP),
//                    realTotalMoney.setScale(2, BigDecimal.ROUND_UP),
//                    request.getOrderSource(),
//                    request.getChannel(),
//                    0,
//                    orderParentNo);
//
//            List<CartProductResponse> products = responses.stream().filter(product -> bankerId.equals(product.getBankerId())).collect(Collectors.toList());
//            // 订单明细
//            products.stream().map(item -> {
//                ProductResponse product = productService.getProductById(item.getId(),request.getPageSourceV2());
//                ProductSpecResponse productSpec = productService.getProductSpecInfoById(item.getSpecId());
//                if (Integer.valueOf(sysConfigUtil.getSysConfig(SysConfigConstants.IS_STOCE_VERIFY)) > 0 && productSpec.getStock() <= 0) {
//                    throw new ApiException(copyWriterConfigUtil.getCopyWriterValue(CopyWriterConstant.INSUFFICIENT_STOCK));
//                }
//                OrdersInfo ordersInfo = ordersService.saveOrdersInfo(orders.getId(), product.getId(), product.getProductName(), product.getProductImg(),
//                        productSpec.getPrice(), product.getOriginalPrice(), product.getWarehouse(), product.getWarehouseName(),
//                        product.getWarehouseRule(), request.getSpecialId(), productSpec.getSkuSpec(), product.getBankerId(),
//                        productSpec.getId(), null, null, null, null,product.getDescr(),
//                        0,request.getPageSourceV2(),null,1,0, productSpec.getCostPrice());
//                try {
//                    // 记录订单规格信息
//                    ProductSpec productSpecs = ordersSpecMapper.selectOrderSpec(request.getProductSpecId());
//                    ordersSpecMapper.insertOrderSpec(productSpecs.getSkuSpec(),orders.getId(),productSpecs.getPrice(),productSpecs.getOriginalPrice(),productSpecs.getCostPrice());
//                }catch (Exception e){
//                    log.error("发送到rabbitmq错误",e);
//                }
//                return ordersInfo;
//            }).collect(Collectors.toList());
//
////            result.add(orders);
//        }
        return result;
    }

    /**
     * 计算订单金额
     * @param bankerId
     * @param responses
     * @return
     */
    private Map<String, BigDecimal> calculationMoney(Integer bankerId, List<CartProductResponse> responses) {
        BigDecimal money = BigDecimal.ZERO;
        BigDecimal realTotalMoney = BigDecimal.ZERO;
        List<CartProductResponse> products = responses.stream().filter(product -> bankerId.equals(product.getBankerId())).collect(Collectors.toList());
        for (CartProductResponse product : products) {
            money = money.add(product.getOriginalPrice());
            realTotalMoney = realTotalMoney.add(product.getPrice());
        }
        Map<String, BigDecimal> result = new HashMap<>();
        result.put("money", money);
        result.put("realTotalMoney", realTotalMoney);
        products = null;
        return result;
    }

    private Map<String, BigDecimal> calculationMoneyByProduct(CartProductResponse response) {
        BigDecimal money = BigDecimal.ZERO;
        BigDecimal realTotalMoney = BigDecimal.ZERO;
        money = money.add(response.getOriginalPrice());
        realTotalMoney = realTotalMoney.add(response.getPrice());
        Map<String, BigDecimal> result = new HashMap<>();
        result.put("money", money);
        result.put("realTotalMoney", realTotalMoney);
        return result;
    }
}
